<?php
namespace app\components;

use yii\db\ActiveRecord;

/**
 * @project kkzc
 * @date 2015-7-3
 * @author xialei <xialeistudio@gmail.com>
 */
class CommonTool
{
    /**
     * 获取模型错误
     * @author xialei <xialeistudio@gmail.com>
     * @param ActiveRecord $model
     * @return array
     */
    public static function  getModelError($model)
    {
        if (!empty($model->errors)) {
            $errors = $model->errors;
            $error = array_shift($errors);
            return $error[0];
        }
        return null;
    }

    /**
     * 输出JSON
     * @author xialei <xialeistudio@gmail.com>
     * @param $data
     * @param int $option
     * @throws \yii\base\ExitException
     */
    public static function json($data, $option = JSON_UNESCAPED_UNICODE)
    {
        echo json_encode($data, $option);
        \Yii::$app->end();
    }

    /**
     * 输出消息
     * @author xialei <xialeistudio@gmail.com>
     * @param $message
     */
    public static function message($message)
    {
        self::json([
            'code' => 0,
            'message' => $message
        ]);
    }

    /**
     * 输出错误
     * @author xialei <xialeistudio@gmail.com>
     * @param $message
     * @param $code
     */
    public static function  error($message, $code)
    {
        self::json([
            'code' => $code,
            'message' => $message
        ]);
    }

    /**
     * 去除手机表情
     * @param string $text
     * @return mixed|string
     */
    public static function emojiFilter($text)
    {
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $text);

        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);

        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);

        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);

        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);

        return $clean_text;
    }

    /**
     * 检测手机号码
     * @author xialei <xialeistudio@gmail.com>
     * @param $str
     * @return int
     */
    public static function isPhone($str)
    {
        return preg_match('/^(\+86)?1[3-9]\d{9}$/', $str);
    }

    /**
     * 检测是否微信访问
     * @return bool
     */
    public static function isWechat()
    {
        return stripos(\Yii::$app->request->userAgent,'MicroMessenger')!==false;
    }
}